import {createAsyncThunk, createSlice, PayloadAction} from '@reduxjs/toolkit'
import LogFactory from "log/LogFactory";
import {requestGet} from "util/request";
import {SecurityUserType} from "type/SecurityUser";
import {Page, PagingData} from "type/Page";
import System from "global/System";
import {StateBaseType} from "../StateBaseType";
import {ReduxStatus} from "../../enum/ReduxStatus";

const log = LogFactory.getLog("userReducer") ;

/**
 * 用户状态类型
 */
export type UserState = StateBaseType<SecurityUserType> ;

const initialState: UserState = {
    data: [] ,
    pageSize: System.getInstance().getUserConfig().userPageSize,
    current: 1,
    total: 0,
    loading: false,
    status: ReduxStatus.INIT,
};

/**
 * 从服务器获取用户信息,异步调用,请求用户分页数据
 */
export const fetchUserPageData = createAsyncThunk(
    'user/fetchUserPageData',
    async (paging: PagingData) => {
        // log.requestDebug("异步获取用户分页数据", paging) ;
        const response = await requestGet<Page<SecurityUserType>>(`/manager/security-user/page/${paging.current}/${paging.pageSize}`) ;
        return response.data ;
    }
) ;

export const userSlice = createSlice({
    name: 'user',
    initialState,
    reducers: {
        /**
         * 根据用户ID删除用户
         * @param state 当前状态
         * @param action 用户ID
         */
        deleteUserById: (state, action: PayloadAction<number>) => {
            // log.debug("删除用户", action.payload) ;
            state.data = state.data.filter(user => user.id !== action.payload) ;
        },
    },
    extraReducers: builder => {
        builder.addCase(fetchUserPageData.pending,(state, action) => {
            // log.debug("从服务器读取用户分页数据准备中");
            state.status = ReduxStatus.PENDING ;
        }) ;
        builder.addCase(fetchUserPageData.fulfilled,(state, action) => {
            // log.debug("从服务器读取用户分页数据成功");
            state.status = ReduxStatus.SUCCESS ;
            state.loading = false ;
            state.data = action.payload.data ;
            state.total = action.payload.total ;
            state.pageSize = action.payload.pageSize ;
            state.current = action.payload.currentPage ;
        }) ;
        builder.addCase(fetchUserPageData.rejected,(state, action) => {
            log.warn("从服务器读取用户分页数据错误");
            state.status = ReduxStatus.FAILED ;
        }) ;
    }
}) ;

export const {deleteUserById } = userSlice.actions ;
export default userSlice.reducer ;